<?php
namespace App\Services;
use EasyWeChat;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use App\Repos\TplmsgRepo;
use Log;

class WechatTpl 
{
	

	/**
	 * 发送红包
	 */
	public static function sendEnvelope($data,$openid)
	{
		//return true;

		// 下面的逻辑是发红包的
		$data['code'] = orderCode('E',$data['user_id']);
		$config  = config('wechat.payment.default');
		$payment = Factory::payment($config);

		$redpack = $payment->redpack;
		$redpackData = [
		    'mch_billno'   => $data['code'],
		    'send_name'    => '活动红包',
		    're_openid'    => $openid,
		    'total_num'    => 1,  //固定为1，可不传
		    'total_amount' => $data['money'],  //单位为分，不小于100
		    'wishing'      => '恭喜发财',		   
		    'act_name'     => '拍十秒',
		    'remark'       => '拍十秒中奖',		    
		];

		$rs = $redpack->sendNormal($redpackData);
		return $rs;
	}

	/**
	 * 企业付款到零钱
	 */
	public static function toBalance($data,$openid)
	{
		$config  = config('wechat.payment.default');
		$app = Factory::payment($config);

		$rs = $app->transfer->toBalance([
		    'partner_trade_no' => date('YmdHis'), // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
		    'openid' => $openid,
		    'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
		    //'re_user_name' => '王小帅', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
		    'amount' => $data['money'], // 企业付款金额，单位为分
		    'desc' => '品质生活 更多快乐 ', // 企业付款操作说明信息。必填
		]);
		return $rs;
	}

	public static function serviceMsg($msg,$openid)
	{
		$app = app('wechat.mini_program');
		$message = new Text($msg);
		$result = $app->customer_service->message($message)->to($openid)->send();
		return $result;
	}

	/**
	 * 获取已经选择了的模板消息
	 */
	public static function tplMsgList()
	{
		$app = app('wechat.mini_program');
		$list = $app->template_message->getTemplates(0, 20);
		if($list['errcode']==0) return $list['list'];
		return false;
		
	}

	/**
	 * 发送模板消息
	 */
	public static function sendTplMsg($code,$msg,$type='')
	{
		$tpl  = TplmsgRepo::find(['code'=>$code]);
		if($tpl) {
			$app  = EasyWeChat::miniProgram();
			if($type=='shop') {
				$app  = EasyWeChat::miniProgram('shop');
			}
			
			$arr  = TplmsgRepo::getKeywords($tpl->id,$msg);
			Log::info('消息模板数据：'.json_encode($arr)); 
			$flag = $app->template_message->send([
			    'touser'      => $msg['openid'],
			    'template_id' => $tpl->template_id,
			    'page'        => 'index',
			    'form_id'     => $msg['form_id'],
			    'data' => $arr,
			]);
			Log::info('消息模板'.$code.'结果：'.json_encode($flag)); 
			return $flag;
		}
	}


	
}